import type { Button } from "@/common/types/button"
import { ElMessage } from "element-plus"
import { computed, ref, watch } from "vue"
import { useRouter } from "vue-router"
import { usePersonaStore } from "@/pinia/stores/persona"

// 定义人设接口
export interface Persona {
  id: string
  name: string
  storeType: string
  createTime: string
  templates: number
  targets: number
  status: "published" | "unpublished"
  hasAvatarConfig: boolean
  audienceConfigStatus: number // 0: 已配置受众画像, 1: 未配置受众画像
}

// 定义店铺类型选项接口
export interface StoreTypeOption {
  label: string
  value: string
}

// 定义表单数据接口
export interface FormData {
  storeType: string
  name: string
}

export function usePersonaMaintenance() {
  // 路由实例
  const router = useRouter()
  const personaStore = usePersonaStore()

  // 响应式状态
  const loading = ref(false)
  const searchKeyword = ref("")
  const selectedStoreType = ref("")
  const showCreateDialog = ref(false)
  const currentEditPersona = ref<Persona | null>(null)

  // 模拟店铺类型选项数据（来自图二）
  const storeTypeOptions: StoreTypeOption[] = [
    { label: "全部类型", value: "" },
    { label: "餐饮美食", value: "餐饮美食" },
    { label: "零售商店", value: "零售商店" },
    { label: "美容美发", value: "美容美发" },
    { label: "健身运动", value: "健身运动" },
    { label: "教育培训", value: "教育培训" }
  ]

  // 模拟人设数据（根据图一）
  const personas = ref<Persona[]>([
    {
      id: "PS001",
      name: "专家型老板",
      storeType: "餐饮美食",
      createTime: "2024-02-01",
      templates: 8,
      targets: 5,
      status: "published",
      hasAvatarConfig: true,
      audienceConfigStatus: 0 // 已配置受众画像
    },
    {
      id: "PS002",
      name: "搞笑测评员",
      storeType: "餐饮美食",
      createTime: "2024-02-05",
      templates: 7,
      targets: 3,
      status: "unpublished",
      hasAvatarConfig: false,
      audienceConfigStatus: 1 // 未配置受众画像
    },
    {
      id: "PS003",
      name: "邻家小姐姐",
      storeType: "零售商店",
      createTime: "2024-02-10",
      templates: 6,
      targets: 4,
      status: "unpublished",
      hasAvatarConfig: false,
      audienceConfigStatus: 1 // 未配置受众画像
    },
    {
      id: "PS004",
      name: "时尚达人",
      storeType: "美容美发",
      createTime: "2024-02-15",
      templates: 5,
      targets: 2,
      status: "unpublished",
      hasAvatarConfig: false,
      audienceConfigStatus: 1 // 未配置受众画像
    }
  ])

  // 过滤后的人设列表
  const filteredPersonas = computed(() => {
    let result = personas.value

    // 根据店铺类型过滤
    if (selectedStoreType.value) {
      result = result.filter(persona => persona.storeType === selectedStoreType.value)
    }

    // 根据搜索关键词过滤
    if (searchKeyword.value.trim()) {
      const keyword = searchKeyword.value.trim().toLowerCase()
      result = result.filter(persona =>
        persona.name.toLowerCase().includes(keyword)
        || persona.storeType.toLowerCase().includes(keyword)
        || persona.id.toLowerCase().includes(keyword)
      )
    }

    return result
  })

  // 头部按钮配置
  const headerButtons: Button[] = [
    {
      text: "新增账号人设",
      type: "primary" as const,
      icon: "Plus",
      onClick: () => openCreateDialog()
    }
  ]

  // 打开新增弹窗
  const openCreateDialog = () => {
    currentEditPersona.value = null
    showCreateDialog.value = true
  }

  // 打开编辑弹窗
  const _openEditDialog = (persona: Persona) => {
    currentEditPersona.value = persona
    showCreateDialog.value = true
  }

  // 关闭弹窗
  const closeDialog = () => {
    showCreateDialog.value = false
    currentEditPersona.value = null
  }

  // 处理新增/编辑人设
  const handleCreatePersona = async (data: FormData) => {
    try {
      loading.value = true

      if (currentEditPersona.value) {
        // 编辑模式
        const index = personas.value.findIndex(p => p.id === currentEditPersona.value!.id)
        if (index !== -1) {
          personas.value[index] = {
            ...personas.value[index],
            name: data.name,
            storeType: data.storeType
          }
        }

        // TODO: 调用更新人设API
        // await updatePersona(currentEditPersona.value.id, data)

        ElMessage.success("人设更新成功")
      } else {
        // 新增模式
        const newPersona: Persona = {
          id: `PS${String(Date.now()).slice(-3).padStart(3, "0")}`,
          name: data.name,
          storeType: data.storeType,
          createTime: new Date().toISOString().split("T")[0],
          templates: 0,
          targets: 0,
          status: "unpublished",
          hasAvatarConfig: false,
          audienceConfigStatus: 1 // 未配置受众画像
        }

        personas.value.unshift(newPersona)

        // TODO: 调用创建人设API
        // await createPersona(data)

        ElMessage.success("人设创建成功")
      }

      closeDialog()
      await refreshData()
    } catch (error) {
      console.error("操作失败:", error)
      ElMessage.error("操作失败，请重试")
    } finally {
      loading.value = false
    }
  }

  // 处理受众画像查看
  const handleViewAudience = (persona: Persona) => {
    // 跳转到受众画像页面，传递人设ID
    router.push({
      path: `/persona-maintenance/${persona.id}/audience`,
      query: { personaName: persona.name }
    })
  }

  // 更新人设状态
  const _updatePersonaStatus = (id: string, status: "published" | "unpublished") => {
    const persona = personas.value.find(p => p.id === id)
    if (persona) {
      persona.status = status
      ElMessage.success(`人设${status === "published" ? "发布" : "取消发布"}成功`)
    }
  }

  // 刷新数据
  const refreshData = async () => {
    try {
      loading.value = true

      // TODO: 调用获取人设列表API
      // const response = await getPersonas()
      // personas.value = response.data

      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500))
    } catch (error) {
      console.error("获取数据失败:", error)
      ElMessage.error("获取数据失败，请重试")
    } finally {
      loading.value = false
    }
  }

  // 监听人设配置状态变化
  watch(() => personaStore.configUpdates, () => {
    // 检查是否有状态更新
    personas.value.forEach((persona) => {
      const configStatus = personaStore.getPersonaConfigStatus(persona.id)
      if (configStatus !== undefined) {
        persona.hasAvatarConfig = configStatus
        persona.audienceConfigStatus = configStatus ? 0 : 1 // 更新受众画像配置状态
        persona.status = configStatus ? "published" : "unpublished"
        // 清除已处理的状态更新
        personaStore.clearPersonaConfigStatus(persona.id)
      }
    })
  }, { deep: true })

  // 初始化数据
  const init = async () => {
    await refreshData()
  }

  return {
    // 响应式状态
    loading,
    searchKeyword,
    selectedStoreType,
    showCreateDialog,
    currentEditPersona,

    // 计算属性
    filteredPersonas,
    storeTypeOptions,
    headerButtons,

    // 方法
    handleCreatePersona,
    openCreateDialog,
    closeDialog,
    handleViewAudience,
    refreshData,
    init
  }
}
